<template>
  <div class="content insitiutions">
    <!-- 标题 -->
    <!-- <div style="margin-bottom:23px">
      <span class="title">机构列表</span>
    </div> -->
    <!-- 卡片内容 -->
    <Card dis-hover>
      <!-- 添加主机构 -->
      <div style="margin-bottom:15px">
        <Button type="primary" @click="addZJG">添加主机构</Button>
        <Modal
          :mask-closable="false"
          v-model="modal1"
           :width="formLeft.isEdit
              ? '900'
              : +formLeft.org_parent_id > 0
              ? '1600'
              : '900'"
          :title="
            formLeft.isEdit
              ? '修改机构信息'
              : +formLeft.org_parent_id > 0
              ? '新增子机构'
              : '新增主机构'
          "
          footer-hide
          @on-visible-change="JGVisibleChange"
        >
        <div v-if="!formLeft.isEdit && +formLeft.org_parent_id > 0">
             <Row :gutter="18">
                <Col span="6">
                  <Input v-model="zjgSearch" placeholder="请输入英文机构名" @on-change="btnDisable()" clearable/>
                  <span v-if="zjgShowTip" class="attribution">
                      {{ zjgTip }}
                  </span>
                </Col>
                <Col span="6">
                  <Button :type="primary" :disabled="dis"   @click="seleZjg" style="margin-bottom:10px">搜索</Button>
                </Col>
              </Row>
              <div v-if="zjgList.length>0">
                 <Table :columns="zjgColumns" :data="zjgList" @on-selection-change="zjgSelect"></Table>
              <!-- 分页 -->
              <div>
                <Page
                  class="td-left"
                  show-elevator
                  show-sizer
                  :total="zjgTotal"
                  :page-size="zjgSize"
                  :page="zjgPage"
                  :current="zjgPage"
                  @on-change="zjgchangedata"
                  @on-page-size-change="zjgchangePagesize"
                />
                  <span class='all-page'>共{{z_total}}条</span>
              </div>
              <div style="clear:both"></div>
              <div slot="footer" class="footer">
                <Button type="text" @click="cancel" style="border:1px solid #3A64FF;margin-right:8px">取消</Button>
                <Button type="primary" @click="ok">{{
                  formLeft.isEdit ? "保存" : "添加"
                }}</Button>
              </div>
            </div>
        </div>
        <div v-else>
          <p class="message">基本信息</p>
          <Form
            v-if="modal1"
            :model="formLeft"
            label-position="right"
            :label-width="100"
            ref="JGForm"
            :rules="ruleValidate"
          >
            <Row :gutter="18">
              <Col span="12">
                <FormItem label="org_id:" prop="org_id">
                  <Input
                    v-model="formLeft.org_id"
                    :disabled="formLeft.isEdit"
                  />
                  <span v-if="isTg && formLeft.org_id != ''" class="isTg">
                    未查询到相关id
                  </span>
                </FormItem>
              </Col>
              <Col span="6">
                <Button
                  type="primary"
                  @click="searchOrgID"
                  v-if="!formLeft.isEdit"
                  >搜索</Button
                >
              </Col>
            </Row>
            <Row>
              <Col span="12">
                <FormItem label="org_name:" prop="org_name">
                  <Input
                    v-model="formLeft.org_name"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="country:" prop="country">
                  <Input
                    v-model="formLeft.country"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="province:" prop="province">
                  <Input
                    v-model="formLeft.province"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="city:" prop="city">
                  <Input
                    v-model="formLeft.city"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="street:" prop="street">
                  <Input
                    v-model="formLeft.street"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="机构类型:" prop="org_type">
                  <Select
                    v-model="formLeft.org_type"
                    placeholder="请选择机构类型"
                    :disabled="formLeft.disabled"
                  >
                    <Option value="高校">高校</Option>
                    <Option value="企业">企业</Option>
                    <Option value="医院">医院</Option>
                    <Option value="研究机构">研究机构</Option>
                    <Option value="其他">其他</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="机构名称:" prop="org_name_cn">
                  <Input
                    v-model="formLeft.org_name_cn"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="国家:" prop="country_cn">
                  <Input
                    v-model="formLeft.country_cn"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="省份:" prop="province_cn">
                  <Input
                    v-model="formLeft.province_cn"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
                <FormItem label="城市:" prop="city_cn">
                  <Input
                    v-model="formLeft.city_cn"
                    :disabled="formLeft.disabled"
                  />
         
                </FormItem>
                <FormItem label="街道:" prop="street_cn">
                  <Input
                    v-model="formLeft.street_cn"
                    :disabled="formLeft.disabled"
                  />
                </FormItem>
              </Col>
            </Row>
          </Form>
          <div slot="footer" class="footer">
            <Button type="text" @click="cancel"  style="border:1px solid #3A64FF;margin-right:8px">取消</Button>
            <Button type="primary" @click="ok">保存</Button>
          </div>
        </div>
        </Modal>
        <!-- 查看记录弹框 -->
        <Modal
          :mask-closable="false"
          width="60%"
          v-model="record"
          title="查看记录"
          footer-hide
          @on-visible-change="JLVisibleChange"
        >
          <Table :columns="columnsrecord" :data="datarecord"></Table>
          <Page
            class="td-left"
            :total="recordTotal"
            show-total
            show-elevator
            :page-size="recordPageSize"
            :page="recordPage"
            :current="recordPage"
            @on-change="Recordchangedata"
            show-sizer
            @on-page-size-change="RecordchangePagesize"
          />
          <div style="clear:both"></div>
        </Modal>
      </div>
      <!-- 表格 -->
      <div>
        <Table
          :columns="columns10"
          :data="data9"
          :row-class-name="rowClassName"
           :loading="loading"
        ></Table>
        <!-- 分页 -->
        <div>
          <Page
            class="td-left"
            :total="total"
            show-total
            show-elevator
            :page-size="page_size"
            :page="page"
            :current="page"
            @on-change="changedata"
            show-sizer
            @on-page-size-change="changePagesize"
          />
        </div>
        <div style="clear:both"></div>
      </div>
    </Card>
  </div>
</template>

<script>
import {
  getDatalist,
  searchOrg,
  addOrUpdateJG,
  deleteAgency,
  recordAgency,
  relation,
  relation2
} from '@/api/institutions'
// import loadingUtils from '@/utils/loading.js'
import expandRow from './table-list'
import './page.css'
export default {
  components: { expandRow },
  data () {
    return {
       loading: true,
       dis: true,
       primary: 'info',
      // org_id:'',
      page_size: 10,
      page: 1,
      total: 0,
      all_total: 0,
      modal1: false,
      addVisable: false,
      record: false,
      z_total:0,
      formLeft: {
        // 添加父级ID 默认为0
        org_parent_id: '0',
        org_id: '',
        org_name: '',
        country: '',
        province: '',
        city: '',
        street: '',
        org_name_cn: '',
        country_cn: '',
        province_cn: '',
        city_cn: '',
        street_cn: '',
        org_type: '',
        disabled: true,
        // 当前打开弹窗是否是编辑状态
        isEdit: false
      },
      // 机构新增和修改弹窗的表单的验证
      ruleValidate: {},
      showMessage: false,
      columns10: [
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row
              }
            })
          }
        },
        {
          title: '机构ID',
          //   align: "center",
          minwidth: 100,
          key: 'org_id'
        },
        {
          title: '机构名称',
          // align: "center",
          width: 300,
          key: 'org_name'
        },
        {
          title: '城市',
          // align: "center",
          minwidth: 200,
          key: 'city'
        },
        {
          title: '国家',
          // align: "center",
          width: 240,
          key: 'country'
        },
        {
          title: '类型',
          // align: "center",
          width: 200,
          key: 'org_type'
        },
        {
          title: '操作',
          // align: "center",
          width: 300,
          render: (h, params) => {
            let add = h(
              'Button',
              {
                props: {
                  type: 'text'
                  // icon: "ios-add-circle-outline"
                },
                style: {
                  color: '#2d8cf0',
                  padding: '0',
                  marginRight: '19px'
                },
                on: {
                  click: () => {
                    // 设置表单得校验规则
                    this.ruleValidate = {
                      org_id: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ]
                    }
                    // 设置父级ID
                    this.formLeft.org_parent_id = params.row.org_id
                    // this.searchJg('', params.row.org_id)
                    this.zjgList = []
                    this.modal1 = true
                    this.dis = true
                    this.primary= "info"
                  }
                }
              },
              '新增'
            )

            let edit = h(
              'Button',
              {
                props: {
                  type: 'text'
                  // icon: "ios-create-outline"
                },
                style: {
                  color: '#2d8cf0',
                  padding: '0',
                  marginRight: '19px'
                },
                on: {
                  click: () => {
                    // 设置表单得校验规则
                    this.ruleValidate = {
                      org_id: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      org_name: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      country: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      province: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      city: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      street: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      org_name_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      country_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      province_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      city_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      street_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      org_type: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ]
                    }
                    this.modal1 = true
                    const temp = params.row
                    // 对应赋值
                    for (const key in this.formLeft) {
                      this.formLeft[key] =  temp[key]?temp[key] + '' || '': ''
                      this.formLeft.org_parent_id = '0'
                    }
                    this.formLeft.disabled = false
                    this.formLeft.isEdit = true
                  }
                }
              },
              '编辑'
            )
            let del = h(
              'Poptip',
              {
                props: {
                  confirm: true,
                  title: '你确定删除吗?',
                  transfer: true
                },
                style: {
                  // marginRight: "5px"
                },
                on: {
                  'on-ok': async () => {
                    const { data: res } = await deleteAgency({
                      org_id: params.row.org_id
                    })
                    if (res.code == 0) {
                      if (res.message) { return this.$Message.warning(res.message) } // 成功的提示
                      this.$Message.success('删除机构成功') // 成功的提示
                      this.getDatalist()
                    }
                  }
                }
              },
              [
                h(
                  'Button',
                  {
                    props: {
                      type: 'text',
                      size: 'small'
                    },
                    style: {
                      color: 'rgb(45, 140, 240)',
                      padding: '0',
                      marginRight: '19px'
                    }
                  },
                  '删除'
                )
              ]
            )

            let task = h(
              'Button',
              {
                props: {
                  type: 'text'
                  // icon: "ios-search-outline"
                },
                style: {
                  color: '#2d8cf0',
                  padding: '0'
                },
                on: {
                  click: () => {
                    this.record = true
                    this.getRecord(params.row.org_id)
                  }
                }
              },
              '查看记录'
            )
            let option = []
            option.push(add)
            option.push(edit)
            option.push(del)
            option.push(task)
            return h('div', option)
          }
        }
      ],
      data9: [],
      // 查看记录
      columnsrecord: [
        {
          title: '编辑人',
          // align: "center",
          key: 'admin_name'
        },
        {
          title: '编辑内容',
          // align: "center",
          key: 'remark',
          render: (h, params) => {
            let strs = []
            let i = 0
            for (let ky in params.row.remark) {
              i++
              return h('div',
                [
                  h('span',i+'.'),
                  h('span', { style: { color: '#3a64ff' } }, this.zd[ky]),
                  h('span', { style: { color: '#000' } }, '由'),
                  h('span', { style: { color: '#f3775e' } }, params.row.remark[ky][0]?params.row.remark[ky][0]:"空"),
                  h('span', { style: { color: '#000' } }, '修改为'),
                  h('span', { style: { color: '#59c692' } }, params.row.remark[ky][1])
                ]
              )
            //  strs.push(`将${this.zd[ky]}从${params.row.remark[ky][0]}修改为${params.row.remark[ky][1]}`)
            }
            // return h('span', strs.join(';'))
          }
        },
        {
          title: '更新时间',
          // align: "center",
          key: 'updated_at'
        }
      ],
      datarecord: [],
      recordPage: 1,
      recordPageSize: 10,
      recordTotal: 0,
      isTg: false,
      // 新增子机构时的参数配置
      zjgList: [], // 可使用的子机构列表
      zjgColumns: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '机构ID',
          width: 200,
          key: 'org_id'
        },
        {
          title: '机构名称',
          width: 500,
          // ellipsis: true,
          key: 'org_name'
        },
        {
          title: '城市',
          // width:100,
          key: 'city'
        },
        {
          title: '国家',
          // width:100,
          key: 'country'
        },
        {
          title: '类型',
          width: 120,
          key: 'org_type'
        }
      ], // 子机构新增时的表格列配置
      zjgTotal: 0, // 子机构新增时分页器的合计数
      zjgPage: 1, // 子机构新增时分页器的页码
      zjgSize: 10, // 子机构新增时分页器每页显示的条数
      zjgSearch: '', // 子机构新增时模糊搜索的条件
      zjgShowTip: false, // 搜索子机构时是否显示错误提示
      zjgTip: '', // 搜索子机构时的错误提示
      zjgChecks: []// 缓存已勾选的子机构
    }
  },
  created () {
    this.getDatalist()
  },
  mounted () {
    this.zd = {
      org_name: '机构名称',
      country: '国家',
      province: '省份',
      city: '城市',
      street: '街道',
      org_name_cn: '机构名称',
      country_cn: '国家',
      province_cn: '省份',
      city_cn: '城市',
      street_cn: '街道',
      org_type: '机构类型'
    }
  },
  methods: {
    btnDisable(){
      console.log(this.zjgSearch)
      if(this.zjgSearch){ 
        this.dis = false
        this.primary = 'primary'
      } else {
        this.primary = 'info'
        this.dis = true
      }
    },
    async getDatalist () {
      let params = {       
        // org_id: "",
        page: this.page,
        page_size: this.page_size
      }
      const {
        data: { data: res }
      } = await getDatalist(params)
      this.data9 = res.data
      this.total = res.total
      this.loading = false
    },
    // 主页面页码
    changedata (val) {
      this.page = val
      this.getDatalist()
    },
    // 主页面每页显示条数
    changePagesize (val) {
      this.page = 1
      this.page_size = val
      this.getDatalist()
    },
    addZJG () {
      // 设置表单得校验规则
      this.ruleValidate = {
        org_id: [
          {
            required: true,
            message: '此项为必填项',
            trigger: 'change'
          }
        ]
      }
      this.modal1 = true
    },
    // 主机构新增的弹窗
    async ok () {
      try {
        // 判断是否时添加子机构
        if (!this.formLeft.isEdit && +this.formLeft.org_parent_id > 0) {
          // 此处表示添加子机构的逻辑
          const tmp = { org_son_ids: this.zjgChecks.map(item => item.org_id) }
          const { data: res1 } = await relation2(tmp, this.formLeft.org_parent_id)
          // 判断新增是否成功
          if (res1.code === 0) {
            if (res1.message) return this.$Message.warning(res1.message) // 成功的提示
            const msg = '新增子机构成功'
            this.modal1 = false // 关闭弹窗
            this.getDatalist() // 重新获取表格数据
            this.$Message.success(msg) // 成功的提示
          }
        } else {
          const validate = await this.$refs.JGForm.validate().catch(res => res)
          // 判断表单验证是否通过 不通过的话给与提示
          if (!validate) return
          // 设置请求的参数对象
          const temp = Object.assign({}, this.formLeft)
          delete temp.org_id
          temp.method = 'add'
          if (this.formLeft.isEdit) temp.method = 'edit'

          // 发送新增的请求
            console.log(this.formLeft.org_id)
            console.log(temp)
          const { data: res } = await addOrUpdateJG({
            org_id: this.formLeft.org_id,
            data: temp
          })

          // 判断新增是否成功
          if (res.code === 0) {
            if (res.message) return this.$Message.warning(res.message) // 成功的提示
            const msg = this.formLeft.isEdit
              ? '修改机构信息成功'
              : +this.formLeft.org_parent_id > 0
                ? '新增子机构成功'
                : '新增主机构成功'
            this.modal1 = false // 关闭弹窗
            this.getDatalist() // 重新获取表格数据
            this.$Message.success(msg) // 成功的提示
          }
        }
      } catch (error) {
        console.log(error)
        this.$Message.success('新增主机构失败：' + error)
      }
    },
    // 关闭主机构的新增弹窗
    cancel () {
      this.modal1 = false
    },
    // 监听机构弹窗的显示状态变化
    JGVisibleChange (flag) {
      if (flag) return
      this.formLeft.org_parent_id = '0'
      this.formLeft.org_id = ''
      this.formLeft.org_name = ''
      this.formLeft.country = ''
      this.formLeft.province = ''
      this.formLeft.city = ''
      this.formLeft.street = ''
      this.formLeft.org_name_cn = ''
      this.formLeft.country_cn = ''
      this.formLeft.province_cn = ''
      this.formLeft.city_cn = ''
      this.formLeft.street_cn = ''
      this.formLeft.org_type = ''
      this.formLeft.disabled = true
      this.formLeft.isEdit = false
      this.isTg = false

      this.zjgTotal = 0 // 子机构新增时分页器的合计数
      this.zjgPage = 1 // 子机构新增时分页器的页码
      //this.zjgSize = 5 // 子机构新增时分页器每页显示的条数
      this.zjgSearch = '' // 子机构新增时模糊搜索的条件
      this.zjgShowTip = false // 搜索子机构时是否显示错误提示
      this.zjgTip = '' // 搜索子机构时的错误提示
      this.zjgChecks = []// 缓存已勾选的子机构
    },
    // 主机构新增弹窗 通过搜索获取orgid
    async searchOrgID () {
      this.$refs.JGForm.validateField('org_id', async validate => {
        if (validate) return
        const {
          data: {
            data: { hits: res }
          }
        } = await searchOrg(this.formLeft.org_id)
        // 判断是否获取到相关数据
        if (res.length == 0) return (this.isTg = true)
        // return this.$Message.warning("输入的org_id不存在，请重新输入");
        this.isTg = false
        const temp = { ...res[0] }

        // 对应赋值
        for (const key in this.formLeft) {
          // 对应赋值时需要跳过org_parent_id的赋值
          if (key != 'org_parent_id' && key != 'isEdit') { this.formLeft[key] = temp._source[key] || temp[key] || '' }
        }
        // 将表单的禁用状态改为false 让用户可修改
        this.formLeft.disabled = false
      })
      // if (!this.formLeft.org_id) return;
      // return this.$Message.warning("请先输入org_id！！");
    },
    //
    JLVisibleChange (flag) {
      if (flag) return
      this.recordPage = 1
      this.recordPageSize = 10
      this.recordID = ''
    },
    // 获取详情记录
    async getRecord (id) {
      this.recordID = id
      let params = {
        org_id: id,
        data: { page: this.recordPage, page_size: this.recordPageSize }
      }
      const {
        data: { data: res }
      } = await recordAgency(params)
      this.datarecord = res.data
      this.recordTotal = res.total
    },
    Recordchangedata (val) {
      this.recordPage = val
      this.getRecord(this.recordID)
    },
    RecordchangePagesize (val) {
      this.recordPage = 1
      this.recordPageSize = val
      this.getRecord(this.recordID)
    },

    // 根据条件模糊搜索机构列表的方法
    async searchJg (key, pid) {
      const { data: res } = await relation({
        keywords: key,
        page: this.zjgPage,
        page_size: this.zjgSize
      }, pid)
      if (res.data.hits.length == 0) {
        this.zjgShowTip = true
        this.zjgTip = '该机构已归属'
      }
      this.zjgShowTip = false
      this.z_total = res.data.total
      // console.log(res.data.total)
      if( res.data.total> 10000){
        this.zjgTotal = 10000
      }else{
       this.zjgTotal = res.data.total
      }
      this.zjgList = res.data.hits.map(item => {
        const obj = {
          org_id: item._source.org_id,
          org_name: item._source.org_name_cn ? item._source.org_name + '---' + item._source.org_name_cn : item._source.org_name,
          org_name_cn: item._source.org_name_cn,
          city: item._source.city_cn ? item._source.city + '---' + item._source.city_cn : item._source.city,
          city_cn: item._source.city_cn,
          country: item._source.country_cn ? item._source.country + '---' + item._source.country_cn : item._source.country,
          country_cn: item._source.country_cn,
          method: 'add',
          org_parent_id: this.formLeft.org_parent_id,
          org_type: item._source.org_type,
          province: item._source.province,
          province_cn: item._source.province_cn,
          street: item._source.street,
          street_cn: item._source.street_cn,
          _checked: false,
          is_exit: item._source.is_exit // 0 不存在 1存在
        }
        if(item._source.is_exit ){
          obj['_disabled'] = true
        } else{
          obj['_disabled'] = false
        }
        return obj
      })
      this.zjgList.forEach(item => {
        item._checked = this.zjgChecks.some(it => it.org_id == item.org_id)
      })
    },
    seleZjg () {
      this.zjgPage = 1
      this.$nextTick(()=> {
        this.searchJg(this.zjgSearch, this.formLeft.org_parent_id)
      })
    },
    // 子机构新增时页码
    zjgchangedata (val) {
      this.zjgPage = val
      this.searchJg(this.zjgSearch, this.formLeft.org_parent_id)
    },
    // 子机构新增时每页显示条数
    zjgchangePagesize (val) {
      this.zjgPage = 1
      this.zjgSize = val
      this.searchJg(this.zjgSearch, this.formLeft.org_parent_id)
    },
    // 勾选子机构表格的复选框的事件处理
    zjgSelect (sel) {
      this.zjgChecks = this.zjgChecks.filter(item => !this.zjgList.some(it => it.org_id == item.org_id))
      this.zjgChecks.push(...sel)
    },

    // 没有子级就没有展开行箭头
    rowClassName (row, index) {
      if (row.subordinates_count === 0) {
        // console.log(1111);
        return 'ivu-table-cell-expand2'
      }
      return ''
    }
  }
}
</script>

<style scoped>
.insitiutions >>> td.ivu-table-expanded-cell {
  padding: 0px 0 0px 50px;
  height: 0;
}

.isTg {
  position: absolute;
  bottom: -29px;
  left: 0;
  width: 228px;
  font-size: 12px;
  color: red;
}

.attribution{
  display: inline-block;
  margin-top: 8px;
  margin-bottom: 3px;
  font-size: 12px;
  color: red;
}
.footer{
  text-align: right;
  border-top: 1px solid #e8eaec;
  padding: 12px 18px;
}
</style>
